package linc.fun.openai.controller.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import linc.fun.openai.annotation.ApiRestController;
import linc.fun.openai.annotation.Captcha;
import linc.fun.openai.config.code.EmailConfig;
import linc.fun.openai.domain.dto.request.LoginByEmailRequest;
import linc.fun.openai.domain.dto.request.RegisterFrontUserForEmailRequest;
import linc.fun.openai.domain.vo.LoginInfoVO;
import linc.fun.openai.domain.vo.UserInfoVO;
import linc.fun.openai.domain.vo.response.R;
import linc.fun.openai.enums.ChatUserRegisterTypeEnum;
import linc.fun.openai.service.ChatUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 前端用户控制器
 */
@Slf4j
@Tag(name = "聊天用户相关")
@ApiRestController("/api/chat_user")
public class ChatUserController {

    @Resource
    private ChatUserService chatUserService;

    @Resource
    private HttpServletResponse response;
    @Resource
    private EmailConfig emailConfig;

    @Operation(summary = "邮件验证回调")
    @GetMapping("/verify_email_code")
    public void verifyEmailCode(@Parameter(description = "邮箱验证码") @RequestParam("code") String code) throws IOException {
        try {
            chatUserService.verifyCode(ChatUserRegisterTypeEnum.EMAIL, code);
            response.sendRedirect(emailConfig.getVerificationResponseUrl() + "?success=true");
        } catch (Exception e) {
            log.error("邮件验证回调: ", e);
            response.sendRedirect(emailConfig.getVerificationResponseUrl() + "?success=false&error_message=" + URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8));
        }
    }

    @Operation(summary = "邮箱注册")
    @Captcha
    @PostMapping("/register_by_email")
    public R<String> registerByEmail(@Validated @RequestBody RegisterFrontUserForEmailRequest request) {
        chatUserService.register(request);
        return R.success("注册成功");
    }

    @Operation(summary = "用户信息")
    @GetMapping("/get_user_info")
    public R<UserInfoVO> getUserInfo() {
        return R.data(chatUserService.getUserInfo());
    }

    @Operation(summary = "邮箱登录")
    @PostMapping("/login_by_email")
    public R<LoginInfoVO> login(@RequestBody @Validated LoginByEmailRequest request) {
        return R.data(chatUserService.login(ChatUserRegisterTypeEnum.EMAIL, request.getUsername(), request.getPassword()));
    }
}
